package com.ll.domain.user.event.consumer;

import com.ll.domain.dingtalk.base.DingTalkMessageBaseService;
import com.ll.domain.dingtalk.biz.DingTalkRobotDomainService;
import com.ll.domain.pk.dto.PkDTO;
import com.ll.domain.pk.event.producer.AddPkEvent;
import com.ll.domain.ranking.dto.RankingDTO;
import com.ll.domain.ranking.enums.RankingTypeEnum;
import com.ll.domain.ranking.producer.CleanRankingEvent;
import com.ll.domain.user.base.UserBaseService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * pk 记录添加
 * @author WuHen
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class CleanRankingEventToUserListener implements ApplicationListener<CleanRankingEvent> {

    private final UserBaseService userBaseService;
    private final DingTalkMessageBaseService dingTalkMessageBaseService;

    @Async
    @Override
    public void onApplicationEvent(CleanRankingEvent addPkEvent) {
        Map<RankingTypeEnum, List<RankingDTO>> topMap = addPkEvent.getTopMap();
        Set<Long> pushUser = new HashSet<>();
        log.info("接收到 PK信息添加事件 map ：{}", topMap);
        for(int index=0; index < 10; index++){
            int integral =  (10 - index) * 10;
            for(RankingTypeEnum type : topMap.keySet()){
                List<RankingDTO> rankingDTOS = topMap.get(type);
                if(rankingDTOS.size() > index){
                    RankingDTO dto = rankingDTOS.get(index);
                    if(!pushUser.contains(dto.getStudentUid())){
                        log.info("-->处理 {} 前 {} 名积分 uid {} , integral {}",type,index+1, dto.getStudentUid(), integral );
                        userBaseService.addIntegral(dto.getStudentUid(), integral);
                    }
                    pushUser.add(dto.getStudentUid());
                }
            }
        }
        dingTalkMessageBaseService.sendRankingClean(topMap);
        log.info("接收到 PK信息添加事件 id ：{} 处理成功", topMap.size());
    }
}
